# ========= 引入基础的模块 ========
from resources_base.module_base.importmodules import *

# ========= 导入数据 =============
from userweb.models import *
# ========= 导入DRF模块 ====================
from rest_framework.views import APIView
from userweb.serializer import *
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
# 导入认证类
from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication
# 导入权限类
from rest_framework.permissions import IsAuthenticated
# 导入获取jwt token模块
from resources_base.module_base import jwt_token
# 导入自定义的认证
from userweb.extensions.auth import MyJwtAuthentication


class LoginView(APIView):
    authentication_classes = []
    def post(self, request, *args, **kwargs):
        # ==== 身份验证，如果身份验证成功 ，返回jwt token
        user_obj = Account.objects.filter(loginid=request.data.get('username')).first()
        # == 判断用户名是否存在
        if not user_obj:
            return Response({'code': 0, 'error': "登录名不存在！"})

        # ==== 验证密码 ====
        if user_obj.loginpwd != request.data.get('password'):
            if not user_obj:
                return Response({'code': 0, 'error': "密码错误！"})

        # ====== 身份验证成功 【生成token】====
        token = jwt_token.create_token({'id':user_obj.loginid, 'name': user_obj.name})
        # 返回
        return Response({'code': 1 , 'token': token})



class AccounViewSet(ModelViewSet):
    queryset = Account.objects.all()
    serializer_class = AccountSerializer


class RolesViewSet(ModelViewSet):
    queryset = Roles.objects.all()
    serializer_class = Roleserializer


class DepartmentViewSet(ModelViewSet):
    queryset = Department.objects.all()
    serializer_class = DepartmentSerializer

    authentication_classes = []


class PositionViewSet(ModelViewSet):
    queryset = Position.objects.all()
    serializer_class = PositionSerializer

